/* Copyright (c) [2020] [ylc]. Licensed under Apache-2.0 License. */

#include "keyDrive.h"

my_key_t mKey[KEY_NUM] = {0};

//按键扫描 由按键任务调用
void key_scan(void)
{
	u8 i;
	for (i = 0; i < KEY_NUM; i++) {
		mKey[i].count <<= 1;
		if (mKey[i].read_port != NULL) {
			mKey[i].count |= mKey[i].read_port();
		}
		if (mKey[i].flags.double_scan) {
			if (++mKey[i].double_ticks_10ms >= 30) { //双击间隔最长300ms，建议200-300
				mKey[i].flags.double_scan = 0;
			}
		}
		if ((mKey[i].count & 0xFF) == 0xFF) { //去抖80ms
			mKey[i].flags.press = 1;
			if (++mKey[i].long_ticks_10ms >= 0xFFF0) {
				mKey[i].long_ticks_10ms = 0xFFF0;
			}
			if (mKey[i].long_ticks_10ms >= KEY_LONG_S * 100) {
				if (!(mKey[i].long_ticks_10ms % 10)) {
					mKey[i].flags.key_long = 1;
				}
			}
			if (mKey[i].long_ticks_10ms >= 100) {
				if (mKey[i].flags.lock_1s == 0) {
					mKey[i].flags.long_1s = 1;
					mKey[i].flags.lock_1s = 1;
				}
			}
			if (mKey[i].long_ticks_10ms >= 200) {
				if (mKey[i].flags.lock_2s == 0) {
					mKey[i].flags.long_2s = 1;
					mKey[i].flags.lock_2s = 1;
				}
			}
			if (mKey[i].long_ticks_10ms >= 600) {
				if (mKey[i].flags.lock_6s == 0) {
					mKey[i].flags.long_6s = 1;
					mKey[i].flags.lock_6s = 1;
				}
			}
		}
		else if (mKey[i].flags.press) {
			if (mKey[i].long_ticks_10ms < 100) {
				if (mKey[i].flags.double_scan) {
					mKey[i].flags.key_double = 1;
					mKey[i].flags.double_scan = 0;
				}
				else {
					mKey[i].flags.key_short = 1;
					mKey[i].flags.double_scan = 1;
					mKey[i].double_ticks_10ms = 0;
				}
			}
			mKey[i].flags.lock_1s = 0;
			mKey[i].flags.lock_2s = 0;
			mKey[i].flags.lock_6s = 0;
			mKey[i].flags.press = 0;
			mKey[i].long_ticks_10ms = 0;
		}
	}
}

//按键处理 放主循环
void Task_key(void)
{
	u8 i;

	if (mTimer.flags.ticks_10ms == 0) return;
	mTimer.flags.ticks_10ms = 0;

	key_scan();

	//按键回调
	for (i = 0; i < KEY_NUM; i++) {
		if (mKey[i].flags.key_short) {
			mKey[i].flags.key_short = 0;
			if (mKey[i].key_short_callback) {
				mKey[i].key_short_callback();
			}
		}
		if (mKey[i].flags.key_double) {
			mKey[i].flags.key_double = 0;
			if (mKey[i].key_double_callback) {
				mKey[i].key_double_callback();
			}
		}
		if (mKey[i].flags.key_long) {
			mKey[i].flags.key_long = 0;
			if (mKey[i].key_long_callback) {
				mKey[i].key_long_callback();
			}
		}
		if (mKey[i].flags.long_1s) {
			mKey[i].flags.long_1s = 0;
			if (mKey[i].key_long_1s_callback) {
				mKey[i].key_long_1s_callback();
			}
		}
		if (mKey[i].flags.long_2s) {
			mKey[i].flags.long_2s = 0;
			if (mKey[i].key_long_2s_callback) {
				mKey[i].key_long_2s_callback();
			}
		}
		if (mKey[i].flags.long_6s) {
			mKey[i].flags.long_6s = 0;
			if (mKey[i].key_long_6s_callback) {
				mKey[i].key_long_6s_callback();
			}
		}
	}
}
